<?php


namespace app\api\controller\wechat;


use learn\services\WechatService;

use learn\services\UtilService;
use app\Request;

//引入模型
use app\models\user\WechatUser;
/**
 * Class WechatController
 * @package app\api\controller\wechat
 */
class WechatController
{
    /**
     * 微信服务
     * @return \think\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function serve()
    {
        return WechatService::serve();
    }
    
    //微信登录h5
    public function auth ()
    {
        return WechatService::oauthService()->redirect();
    }


    /**
     * 通过code获取用户信息
     */
    public function tologin (Request $request)
    {
        list($code) = UtilService::getMore([['code','']],$request, true);
        
        $user = WechatService::oauthService()->user()->toArray();
        $data['openid'] = $user['id'];
        $data['nickname'] = $user['name'];
        $data['avatar'] = $user['avatar'];
        $data['add_time'] = time();
        $data['sex'] = $user['original']['sex'];
        $data['city'] = $user['original']['city'];
        $data['province'] = $user['original']['province'];
        $data['country'] = $user['original']['country'];

        return app("json")->success(compact('data'));
    }

    /**
     * 注册微信信息
     */
    public function goLogin(Request $request)
    {
        $data = UtilService::postMore([
            ['openid',0],
            ['nickname',''],
            ['avatar',''],
            ['add_time',''],
            ['sex',''],
            ['city',''],
            ['province',''],
            ['country',''],
        ]);
        if ($data['openid'] == 0) return app("json")->fail("没有微信信息");
        $uid = $request->uid();
        if (WechatUser::UserHas($data['openid'])) {
            //没有用户
            $data['uid'] = $uid;
            WechatUser::create($data);
        }else{
            WechatUser::create(['nickname'=>$data['nickname'],"avatar"=>$data['avatar']],['uid'=>$uid]);
        }
        return app("json")->success("注册微信信息成功");
    }
    
}